/**
 * 
 */
package com.geezdata.cps.ttk.core.command;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.cqrs.command.Command;
import com.geezdata.cps.ttk.common.enums.TtkErrorCodeEnum;
import com.geezdata.cps.ttk.common.request.CreateOrUpdateSharerRequest;
import com.geezdata.cps.ttk.common.response.CreateOrUpdateSharerResult;
import com.geezdata.cps.ttk.common.vo.AES;
import com.geezdata.cps.ttk.common.vo.SharerUserInfoReqVO;
import com.geezdata.cps.ttk.domain.domain.OpenUser;
import com.geezdata.cps.ttk.domain.domain.Sharer;
import com.geezdata.cps.ttk.domain.factory.SharerFactory;
import com.geezdata.cps.ttk.mapper.mapper.SharerMapper;
import com.geezdata.cps.ttk.query.query.OpenUserService;


@Service
public class CreateOrUpdateSharerCommand implements Command<CreateOrUpdateSharerRequest, CreateOrUpdateSharerResult>{
    private static final Logger logger = LoggerFactory.getLogger(CreateOrUpdateSharerCommand.class);
    @Autowired
    private SharerMapper sharerMapper;
    @Autowired
    private OpenUserService openUserService;

    @Transactional
	@Override
	public BaseResponse<CreateOrUpdateSharerResult> execute(CreateOrUpdateSharerRequest request) {
        CreateOrUpdateSharerResult result =new CreateOrUpdateSharerResult();
        if(request.getSessionKey() == null) {
        	OpenUser openUser = openUserService.getRecentOpenUserByOpenId(request.getOpenId());
        	request.setSessionKey(openUser.getSessionKey());
        }
        JSONObject resUserInfo = decipherByUserInfo(request.getSessionKey(), request.getUserInfo());
        Sharer sharer = JSONObject.toJavaObject(resUserInfo,Sharer.class);
        if(sharer == null) {
        	OpenUser openUser = openUserService.getRecentOpenUserByOpenId(request.getOpenId());
        	request.setSessionKey(openUser.getSessionKey());
        	resUserInfo = decipherByUserInfo(request.getSessionKey(), request.getUserInfo());
        	sharer = JSONObject.toJavaObject(resUserInfo, Sharer.class);
            if(sharer == null) {
            	return BaseResponse.error(TtkErrorCodeEnum.SESSION_EXPIRED.getCode(), TtkErrorCodeEnum.SESSION_EXPIRED.getDesc());
            }
        }
        if(StringUtils.isNotBlank(request.getRefererId())) {
        	sharer.setRefererId(Long.parseLong(request.getRefererId()));
        }
        result.setUnionId(sharer.getUnionId());
        sharer.setSessionKey(request.getSessionKey());
        sharer.setOpenId(request.getOpenId());
        sharer.setUnionId(sharer.getUnionId());
        sharer.setAvatarUrl(sharer.getAvatarUrl());
        sharer.setNickName(sharer.getNickName());
        Sharer existSharer = testIfExistSharer(request.getOpenId());
        
        Sharer share = SharerFactory.newInstance(sharer, existSharer);
        createOrUpdateSharer(existSharer, share);
        if(existSharer != null) {
        	result.setIsNew(0);
        }else {
        	result.setIsNew(1);
        } 
        result.setSharerId(share.getSharerId());
		return BaseResponse.success(result);
	}

	private JSONObject decipherByUserInfo(String session_key,SharerUserInfoReqVO request) {
        String  encryptedData = request.getEncryptedData();
        String iv = request.getIv();
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        // 加密秘钥
        byte[] aeskey = Base64.decodeBase64(session_key);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        String newuserInfo = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(dataByte, aeskey, ivByte);
            if (null != resultByte && resultByte.length > 0) {
                newuserInfo = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(newuserInfo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
    private Sharer testIfExistSharer(String openId) {
        Sharer exsitSharer = null;
        Sharer condition =new Sharer();
        if(openId!=null) {
            condition.setOpenId(openId);
            exsitSharer = sharerMapper.selectOne(condition);
        }
        return exsitSharer;
    }
    private void createOrUpdateSharer(Sharer existSharer, Sharer sharer) {
        if (existSharer == null) {
            sharerMapper.insert(sharer);
        } else {
            sharerMapper.updateByPrimaryKey(sharer);
        }
    }
}
